package com.funtl.oauth2.server.config.service;

import com.funtl.oauth2.server.domain.TbPermission;
import com.funtl.oauth2.server.domain.TbUser;
import com.funtl.oauth2.server.service.TbPermissionService;
import com.funtl.oauth2.server.service.TbUserService;
import org.assertj.core.util.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author: Han.Fu
 * @TIME: 2019/7/15  20:01
 * @Description:  将我们的模型进行oauth2.0的接口进行对接
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    // 查询用户
    @Autowired
    private TbUserService tbUserService;

    // 查询权限
    @Autowired
    private TbPermissionService tbPermissionService;

    //将我们的东西从数据库取出来,给到oauth2.0模型(认证和授权)
    // 认证和授权一起管理
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        System.out.println("收到的账号是:"+ username);
        TbUser tbUser = tbUserService.getByUsername(username);
        List<GrantedAuthority> grantedAuthorities = Lists.newArrayList();
        if (tbUser != null) {
            List<TbPermission> tbPermissions = tbPermissionService.selectByUserId(tbUser.getId());
            tbPermissions.forEach(tbPermission -> {
                GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(tbPermission.getEnname());
                //这里add,就有权限了(授权),将此用户的所有权限添加进权限管理里面,交给oauth2进行管理
                grantedAuthorities.add(grantedAuthority);
            });
        }
        //认证是交给框架来完成的,所以这里直接就return User
        return new User(tbUser.getUsername(), tbUser.getPassword(), grantedAuthorities);
    }
}
